<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
namespace Admin\Controller;
use Admin\Service\ScoreSheetService;
use Admin\Service\SheetCommentService;
use Admin\Service\SheetRecordService;
use Think\Controller;
use Admin\Service\SheetService;
use Admin\Service\ImageSheetService;
use Admin\Service\TagSheetService;
use Think\Page;

/**
 * 曲谱控制器
 * @author Administrator
 *
 */
class SheetController extends AdminController {

    public function index($order = 'id', $sort = 1)
    {
        if ($sort == 2) {
            $orderSort = $order . ' desc, id asc';
        } else {
            $orderSort = $order;
        }
        $keywords = explode(' ', I('name'));
        foreach ($keywords as $key => $keyword) {
            $keywordArr[] = array('like', '%'.$keyword.'%');
        }
        $model = M('Sheet');
        $map = array(
            'name' => $keywordArr,
            'is_delete' => 0
        );
    
        /*$list   = $this->lists('Sheet', $map, $orderSort);*/
        //重写分页
        $query = $model->where($map)->field('count(*)')->select();
        $count = $query[0]['count(*)'];
        $listRows = 15;
        $page = new Page($count, $listRows);
        if($count>$listRows){
            $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p =$page->show();

        $list = $model->where($map)->limit($page->firstRow.','.$page->listRows)->order($orderSort)->select();

        $service = new SheetService();


        //补充曲谱信息
        $list = $service->fillInfo($list, $order, $sort);
        $this->assign('_list', $list);
        $this->assign('_page', $p? $p: '');
        $this->assign('_total',$count);


        $this->assign('_condition', I('post.'));
        $this->meta_title = '曲谱信息';
        $this->display();
    
    
    }
    
    /**
     * 启用／禁用
     * @param string $method
     */
    public function changeStatus($method=null){
        $id = array_unique((array)I('id',0));
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        $map['id'] =   array('in',$id);
        
        $sheetService = new SheetService();
        
        switch ( strtolower($method) ){
            case 'submit':
                $sheetService->submit($map);
                break;
            case 'enabled':
                break;
            default:
                $this->error('参数非法');
        }
        $this->success("提交成功");
    }
    
    /**
     * 保存谱单
     */
    public function add(){
        if(IS_POST){
            $service = new SheetService();
            try{
                $id = $service->add();
                $this->success('新增成功', U('Admin/Sheet/index'));
            } catch(\Exception $e){
                $this->error($e->getMessage());
            }
        } else {
            $this->meta_title = '新建曲谱';
            $this->display();
        }
    }
    
    
    public function edit($id = 0){
    
        if(IS_POST){
            $service = new SheetService();
            try{
                $id = $service->edit();
                $this->success('编辑成功', U('Admin/Sheet/index'));
            } catch(\Exception $e){
                $this->error($e->getMessage());
            }
        } else {
            if($id == 0) {
                $this->error('无效的参数');
            }
            
            $data = M('Sheet')->find($id);
            if(false === $data){
                $this->error("获取曲谱信息错误");
            }
            
            //补全标签数据
            $sheetIdList = array($id);
            $tagSheetService = new TagSheetService();
            $tagMap = $tagSheetService->getTagsBySheetIds($sheetIdList);
            $data['tags'] = $tagMap[$id];
            
            $this->assign('data',$data);
            $this->meta_title = '编辑曲谱';
            $this->display();
        }
    
    }
    
    
    public function getImages($sheet_id = 0 ){
        $cond = array(
            'sheet_id' => $sheet_id,
            'is_delete' => 0
        );
        $imgSheet = M('ImageSheet')->where($cond)->select();
        $img_ids = array_column($imgSheet, "image_id");
        
        $map['id'] = array('in', $img_ids);
        $map['is_delete'] = 0;
        $images = M('Image')->where($map)->order('listorder')->select();
        $initialPreview = array_column($images, "url");
        
        $initialPreviewConfig = array();
        foreach ($images as $key => $image) {
            $initialPreviewConfig[$key] = array(
                "caption"   => $image['name'],
                "size"      => $image['size'],
                "url"       => U('Admin/Sheet/removeImage','sheet_id='.$sheet_id.'&image_id='.$image['id']),
                "key"       => $image['id'],
            );
        }
         
        
        $data = array(
            "initialPreview"=>$initialPreview,
            "initialPreviewConfig"=>$initialPreviewConfig
        );
        
        $this->success($data);
    }
    
    public function removeImage($sheet_id = 0 , $image_id = 0){
        $service = new ImageSheetService();
        $rowCount = $service->delete($image_id, $sheet_id);
        $this->success($image_id);
    }
    
    public function del(){
    
        $id = array_unique((array)I('id',0));
    
        $id = is_array($id) ? implode(',',$id) : $id;
        if (empty($id)) {
            $this->error('请选择要操作的数据!');
        }
        $map = array('id' => array('in', $id) );
         
        if(M('Sheet')->where($map)->delete()){
            $this->success('删除成功');
        } else {
            $this->error('删除失败！');
        }
    }

    public function detail($id = 0)
    {
        if($id == 0) {
            $this->error('无效的参数');
        }

        $data = M('Sheet')->find($id);
        if(false === $data){
            $this->error("获取曲谱信息错误");
        }

        //获取图片
        $cond = array(
            'sheet_id' => $id,
            'is_delete' => 0
        );
        $imgSheet = M('ImageSheet')->where($cond)->select();
        $img_ids = array_column($imgSheet, "image_id");

        $map['id'] = array('in', $img_ids);
        $images = M('Image')->where($map)->order('listorder')->select();

        foreach ($images as $key => $image) {
            $data['image'][$key]['id'] = $image['id'];
            $data['image'][$key]['url'] = $image['url'];
        }

        //补全标签数据
        $sheetIdList = array($id);
        $tagSheetService = new TagSheetService();
        $tagMap = $tagSheetService->getTagsBySheetIds($sheetIdList);
        $data['tags'] = $tagMap[$id];
        $this->assign('data',$data);
        $this->meta_title = '曲谱详情';
        $this->display();
    }

    /**
     * 修改图片顺序
     */
    public function sortSheetImg()
    {
        $param = I('post.');
        $sheet_id = $param['sheet_id'];
        $image_ids = $param['image_id'];

        foreach ($image_ids as $key => $image_id) {
            $data['listorder'] = (int)$key + 1;
            $map = array(
                'id' => $image_id
            );
            $id = M('Image')->where($map)->save($data);
        }
        $this->success($id);
    }

    /**
     * 手动刷新统计数据
     */
    public function count()
    {
        $model = M('Sheet');

        $list = M('SheetRecord')->field('sheet_id')->group('sheet_id')->select();
        $recordIds = array_column($list, 'sheet_id');
        $list = M('SheetFavorite')->field('sheet_id')->group('sheet_id')->select();
        $favIds = array_column($list, 'sheet_id');
        $list = M('SheetComment')->field('sheet_id')->group('sheet_id')->select();
        $commentIds = array_column($list, 'sheet_id');
        $map = array(
            '_string' => 'comment_count <> 0 OR fav_count <> 0 OR record_count <> 0'
        );
        $list = $model->field('id')->where($map)->select();
        $sheetIds = array_column($list, 'id');
        $ids = array_unique(array_merge($recordIds, $favIds, $commentIds, $sheetIds));


        //1.获取评论数
        $commentService = new SheetCommentService();
        $sheetCommentCount = $commentService->multiCommentCount($ids);
        //2.获取收藏数
        $favService = new ScoreSheetService();
        $sheetFavCount = $favService->multiFavCount($ids);
        //3.获取录音数
        $recordService = new SheetRecordService();
        $sheetRecordCount = $recordService->multiRecordCount($ids);
        $sheetList = array();
        foreach ($ids as $key => $sheet) {
            $sheetList[$key]['id'] = $sheet;
            $sheetList[$key]['comment_count'] = $sheetCommentCount[$sheet] ? $sheetCommentCount[$sheet] : 0;
            $sheetList[$key]['fav_count'] = $sheetFavCount[$sheet] ? $sheetFavCount[$sheet] : 0;
            $sheetList[$key]['record_count'] = $sheetRecordCount[$sheet] ? $sheetRecordCount[$sheet] : 0;
        }

        foreach ($sheetList as $sheet) {
            $model->where(array('id'=>$sheet['id']))->save($sheet);
        }
        $this->success('刷新成功');

        /*//获取有评论的曲谱
        $commentModel = M('SheetComment');
        $comment = $commentModel->field('sheet_id, count(*)')->where($map)->group('sheet_id')->select();
        foreach ($comment as $val) {
            $sheet['comment_count'] =  $val['count(*)'];
            $sheet['id'] = $val['sheet_id'];
            $res[] = $model->where(array('id'=>$sheet['id']))->save($sheet);
        }
        //获取被收藏的曲谱
        $favModel = M('ScoreSheet');
        $fav = $favModel->field('sheet_id, count(*)')->where($map)->group('sheet_id')->select();
        foreach ($fav as $val1) {
            $favSheet['id'] = $val1['sheet_id'];
            $favSheet['fav_count'] = $val1['count(*)'];
            $favRes[] = $model->where(array('id'=>$favSheet['id']))->save($favSheet);
        }
        //获取有录音的曲谱
        $recordModel = M('SheetRecord');
        $record = $recordModel->field('sheet_id, count(*)')->where($map)->group('sheet_id')->select();
        foreach ($record as $val2) {
            $recordSheet['id'] = $val2['sheet_id'];
            $recordSheet['record_count'] = $val2['count(*)'];
            $recRes[] = $model->where(array('id'=>$recordSheet['id']))->save($recordSheet);
        }*/
    }

}
